<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <!-- 申请标题搜索项 -->
      <el-form-item label="申请标题" prop="applicationTitle">
        <el-input
          v-model="queryParams.applicationTitle"
          placeholder="请输入申请标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="申请标题" align="center" prop="applicationTitle" width="200px" />
      <el-table-column label="申请原因" align="center" prop="applicationReason" width="200px" />
      <el-table-column label="应用场景" align="center" prop="applicationScenario" width="200px" />
      <el-table-column label="使用时间" align="center" width="240px">
        <template #default="scope">
          {{ formatDateRange(scope.row.useTimeStart, scope.row.useTimeEnd) }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="150px" />
      <el-table-column label="系统名称" align="center" prop="systemName" width="180px" />
      <el-table-column label="系统IP" align="center" prop="systemIp" width="150px" />
      <el-table-column label="等保级别" align="center" prop="levelProtectionLevel" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PROTECTION_LEVEL" :value="scope.row.levelProtectionLevel" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DEMAND_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="150px">
        <template #default="scope">
          <el-button link type="danger" @click="openReplyDialog(scope.row.id)"> 回复 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 回复弹窗 -->
  <el-dialog v-model="replyDialogVisible" title="回复" width="500px">
    <el-form
      ref="replyFormRef"
      :model="replyForm"
      :rules="replyFormRules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="回复内容" prop="replyContent">
        <el-input
          v-model="replyForm.replyContent"
          type="textarea"
          :rows="5"
          placeholder="请输入回复内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="replyDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitReply" :loading="replyLoading">提交</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import { getQnaList, getQnaReply, getQnaDetail } from '@/api/business/application'
import { onMounted, ref, reactive, nextTick } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useI18n } from '@/hooks/web/useI18n'

/** 应用申请列表 */
defineOptions({ name: 'ApplicationList' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const replyDialogVisible = ref(false)
const replyFormRef = ref()
const replyLoading = ref(false)
const replyForm = reactive({
  replyContent: '',
  id: '' // 存储要回复的记录ID
})
const replyFormRules = reactive({
  replyContent: [{ required: true, message: '回复内容不能为空', trigger: 'blur' }]
})

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  applicationTitle: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 格式化日期范围 */
const formatDateRange = (start?: string, end?: string) => {
  // 提取年月日部分的辅助函数
  const extractDatePart = (dateString?: string) => {
    if (!dateString) return ''
    // 检查是否包含空格，提取年月日部分
    const datePart = dateString.split(' ')[0]
    return datePart
  }

  if (!start) return ''
  if (!end) return extractDatePart(start)
  return `${extractDatePart(start)} - ${extractDatePart(end)}`
}

const openReplyDialog = (id: string) => {
  replyForm.id = id
  replyForm.replyContent = ''
  replyDialogVisible.value = true
  // 获取详情
  getQnaDetail({ id: replyForm.id }).then((res) => {
    if (res) {
      replyForm.replyContent = res.replyContent
    }
  })
  // 重置表单验证
  nextTick(() => {
    replyFormRef.value?.resetFields()
  })
}

/** 提交回复 */
const submitReply = async () => {
  await replyFormRef.value.validate()
  replyLoading.value = true
  try {
    // 调用getQnaReply接口，传递回复内容和ID
    await getQnaReply({
      id: replyForm.id,
      replyContent: replyForm.replyContent
    })
    message.success('回复成功')
    replyDialogVisible.value = false
    // 刷新列表
    getList()
  } catch (error) {
    message.error('回复失败，请重试')
  } finally {
    replyLoading.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getQnaList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  // 这里假设form组件已经存在，实际项目中需要引入并使用正确的表单组件
  if (formRef.value) {
    formRef.value.open(type, id)
  } else {
    message.warning('表单组件未加载')
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Application[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

/** 初始化 **/
onMounted(async () => {
  getList()
})
</script>
